﻿using Demo.OrderManager.Orders;
using Demo.OrderManager.Orders.Dto;
using Demo.Permissions;
using Demo.ProductManager.Products;
using Demo.ProductManager.Products.Dto;
using Demo.Store.Application.Contracts.Store;
using Demo.Store.Application.Contracts.Store.Dto;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;

namespace Demo.Store.Application;

/// <summary>
/// 订单管理应用服务
/// </summary>
public class StoreOrderAppService : ApplicationService, IStoreOrderAppService
{
    private IOrderAppService _orderAppService;
    private IProductAppService _productAppService;

    public StoreOrderAppService(IOrderAppService orderAppService, IProductAppService productAppService)
    {
        _orderAppService = orderAppService;
        _productAppService = productAppService;
    }

    /// <summary>
    /// 创建订单
    /// </summary>
    /// <param name="input">输入对象</param>
    /// <returns>创建结果</returns>
    public async Task<bool> CreateAsync(StoreOrderCreateDto input)
    {
        foreach (var item in input.Products)
        {
            //判断是否为有效的产品ID
            _productAppService.GetAsync(item.ProductId);
        }

        var order = ObjectMapper.Map<StoreOrderCreateDto, OrderCreateDto>(input);
        var ret = await _orderAppService.CreateAsync(order);
        return ret != null;
    }

    /// <summary>
    /// 分页查询订单列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    /// <exception cref="NotImplementedException"></exception>
    [CusPermission(PermissionLab.ORDER_SELECT)]
    public async Task<PagedResultDto<StoreOrderDto>> GetListAsync(PagedAndSortedResultRequestDto input)
    {
        var ret = await _orderAppService.GetListAsync(input);
        return new PagedResultDto<StoreOrderDto>
        {
            TotalCount = ret.TotalCount,
            Items = ObjectMapper.Map<IReadOnlyList<OrderDto>, List<StoreOrderDto>>(ret.Items)
        };
    }

    /// <summary>
    /// 获取订单详情
    /// </summary>
    /// <param name="id">订单编号</param>
    /// <returns></returns>
    public async Task<StoreOrderDetailDto> GetAsync(Guid id)
    {
        var order = await _orderAppService.GetAsync(id);
        var result = ObjectMapper.Map<OrderDetailDto, StoreOrderDetailDto>(order);
        foreach (var item in order.Products)
        {
            var product = await _productAppService.GetAsync(item.ProductId);
            var productDto = ObjectMapper.Map<ProductDto, StoreOrderProductsDto>(product);
            productDto.Count = item.Count;
            result.Products.Add(productDto);
            result.TotalPrice += product.Price * item.Count;
        }

        return result;
    }
}